package cmd

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strings"
	"time"
	"undertow_accesslog_analyse/analyse"
)

func Setup(result analyse.AnalyseResult) {
	accpet(result)
}

func welcome() {
	fmt.Print("进入cmd模式\n" +
		"1.总时间倒序\n" +
		"2.总时间正序\n" +
		"3.平均时间倒序\n" +
		"4.平均时间正序\n" +
		"5.请求次数倒序\n" +
		"6.请求次数正序\n")
}

// 接受输入并且返回信息
func accpet(result analyse.AnalyseResult) {
	welcome()
	<-time.After(200 * time.Millisecond)
	fmt.Println()
	fmt.Print("> ")
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		input := scanner.Text()
		input = strings.TrimSpace(input)
		switch input {
		case "1":
			TotalTimeDesc(result)
		case "2":
			TotalTimeAsc(result)
		case "3":
			AvgTimeDesc(result)
		case "4":
			AvgTimeAsc(result)
		case "5":
			CountDesc(result)
		case "6":
			CountAsc(result)
		default:
			fmt.Println("unknow commend")
		}
	}
}

func TotalTimeDesc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].TotalTime > result.Items[j].TotalTime
	})
	print(result)
}

func TotalTimeAsc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].TotalTime < result.Items[j].TotalTime
	})
	print(result)
}

func AvgTimeDesc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].GetAvgTime() > result.Items[j].GetAvgTime()
	})
	print(result)
}

func AvgTimeAsc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].GetAvgTime() < result.Items[j].GetAvgTime()
	})
	print(result)
}

func CountDesc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].Count > result.Items[j].Count
	})
	print(result)
}

func CountAsc(result analyse.AnalyseResult) {
	sort.Slice(result.Items, func(i, j int) bool {
		return result.Items[i].Count < result.Items[j].Count
	})
	print(result)
}

func print(analyse analyse.AnalyseResult) {
	fmt.Printf("|%-6v|%-12v|%-50v|%-12v|\n", "次数", "总时间", "请求链接", "平均时间")
	for _, item := range analyse.Items {
		fmt.Printf("|%-6v|%-12v|%-50v|%-12v|\n", item.Count, item.TotalTime, item.RequestPath, item.GetAvgTime())
	}
}
